<template>
  <div style="width: 100%">
    <div style="width: 250px; float: left">
      <a-card
        @contextDictionary.prevent
        size="small"
        class="eip-admin-card-small"
      >
        <div slot="title">
          <a-space>
            <a-input-search
              v-model="department.key"
              :allowClear="true"
              placeholder="名称/拼音模糊搜索"
              @change="departmentSearch"
            />
            <a-tooltip title="刷新">
              <a-button type="primary" @click="init">
                <a-icon type="redo" />
              </a-button>
            </a-tooltip>
          </a-space>
        </div>
        <a-spin
          :spinning="department.spinning"
          :delay="0"
          :style="department.style"
        >
          <div>
            <a-directory-tree
              v-if="!department.spinning"
              :expandAction="false"
              :defaultExpandedKeys="[
                department.data.length > 0 ? department.data[0].key : '',
              ]"
              :tree-data="department.data"
              :icon="icon"
              @select="select"
            ></a-directory-tree>
          </div>
        </a-spin>
      </a-card>
    </div>
    <div class="eip-admin-card-tree-left">
      <vxe-grid v-bind="grid" ref="xGrid">
        <template #toolbar_buttons>
          <eip-toolbar
            @asyncUser="asyncUser"
            @asyncUserToSystem="asyncUserToSystem"
            @bind="bindUser"
            @chosenOrganizationTransfer="chosenOrganizationTransfer"
          ></eip-toolbar>
        </template>
        <template #toolbar_tools> </template>
        <template #loading>
          <a-spin></a-spin>
        </template>
        <template #empty>
          <eip-empty />
        </template>

        <template #avatar="{ row }">
          <vxe-image
            :src="row.avatar"
            style="width: 32px; height: 32px; border-radius: 50%"
          ></vxe-image>
        </template>

        <template #systemUserId="{ row }">
          <a-tag
            v-if="!row.systemUserId"
            @click="userBind(row)"
            :color="row.systemUserId ? '#2db7f5' : '#f50'"
          >
            {{ row.systemUserId ? "解绑" : "去绑定" }}
          </a-tag>
          <span class="run-list-user" v-if="row.systemUserId">
            <a-tag @click="userDetail(row)" :closable="false">
              <img class="img" v-real-img-user="row.bindHeadImage" />
              <label style="vertical-align: middle">{{
                row.bindUserName
              }}</label>
            </a-tag>
          </span>
          <a-tooltip v-if="row.systemUserId" title="解绑">
            <a-popconfirm
              title="确定取消绑定"
              ok-text="确定"
              cancel-text="取消"
              @confirm="userBind(row)"
            >
              <a-button
                type="danger"
                shape="circle"
                icon="delete"
                size="small"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
        <template #operate="{ row }">
          <a-tooltip
            @click="tableUpdateRow(row)"
            title="编辑"
            v-if="visible.update"
          >
            <label class="text-eip eip-cursor-pointer">编辑</label>
          </a-tooltip>
          <a-divider type="vertical" v-if="visible.update" />
          <a-tooltip title="删除" v-if="visible.del" @click="tableDelRow(row)">
            <label class="text-red eip-cursor-pointer">删除</label>
          </a-tooltip>
        </template>
      </vxe-grid>
    </div>
    <eip-organization
      v-if="options.visible"
      :visible.sync="options.visible"
      :multiple="false"
      :range="0"
      title="选择组织架构"
      @ok="chosenOrganizationOk"
    ></eip-organization>
    <detail
      ref="detail"
      v-if="detail.visible"
      :visible.sync="detail.visible"
      :userId="detail.userId"
      :title="detail.title"
      :privilegeMaster="privilege.master"
      :privilegeMasterValue="privilege.masterValue"
      @save="operateStatus"
    >
    </detail>

    <eip-user
      v-if="user.visible"
      :multiple="false"
      :visible.sync="user.visible"
      :chosen="user.chosen"
      title="选择人员"
      @ok="chosenUserOk"
    ></eip-user>
  </div>
</template>

<script>
import {
  query,
  tree,
  async,
  asyncToSystem,
  bindUserId,
} from "@/services/wechat/work/user/list";

import detail from "@/pages/system/user/detail";

import { selectTableRow, operationConfirm } from "@/utils/util";
export default {
  data() {
    return {
      user: {
        visible: false,
        chosen: [],
        threeUserId: null,
      },
      detail: {
        visible: false,
        userId: "",
        title: "",
      },
      privilege: {
        master: this.eipPrivilegeMaster.user,
        masterValue: null,
      },
      options: {
        visible: false,
        userIds: [],
      },
      department: {
        key: "",
        style: {
          overflow: "auto",
          height: this.eipTableHeight() - 60 + "px",
        },
        data: [],
        original: [],
        spinning: true,
      },
      grid: {
        id: "wechatWorkUser",
        loading: true,
        height: this.eipTableHeight(),
        sortConfig: {
          remote: true,
        },
        pagerConfig: {},
        printConfig: {},
        exportConfig: {},
        filterConfig: {
          remote: true,
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_buttons",
            tools: "toolbar_tools",
          },
        },
        columns: [
          { type: "seq", width: 60, fixed: "left" },
          {
            field: "platformUserId",
            title: "企业微信用户Id",
            width: 220,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "name",
            title: "名称",
            width: 120,
            sortable: true,
            showOverflow: "ellipsis",
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "avatar",
            title: "头像",
            width: 120,
            textalign: "center",
            sortable: true,
            showOverflow: "ellipsis",
            slots: {
              default: "avatar",
            },
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "avatar",
                  key: null,
                  op: "cn",
                  write: null,
                },
              },
            ],
          },
          {
            field: "systemUserId",
            title: "绑定用户",
            width: 160,
            sortable: true,
            showOverflow: "ellipsis",
            slots: {
              default: "systemUserId",
            },
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "stateCode",
            title: "国际电话区号",
            width: 150,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "mobile",
            title: "电话号码",
            width: 120,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "jobNumber",
            title: "员工工号",
            width: 120,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "title",
            title: "职位",
            width: 180,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "remark",
            title: "邮箱",
            width: 120,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "organizationNames",
            title: "所属部门",
            width: 120,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "createUserName",
            title: "创建人",
            width: 150,
            sortable: true,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "createTime",
            title: "创建时间",
            width: 150,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
          {
            field: "updateUserName",
            title: "修改人",
            width: 150,
            sortable: true,
            filterRender: {
              name: "MLFilterRender",
            },
            filters: [
              {
                data: {
                  type: "input",
                  key: null,
                  op: "cn",
                  write: null,
                  options: [],
                },
              },
            ],
          },
          {
            field: "updateTime",
            title: "修改时间",
            width: 150,
            sortable: true,
            filterRender: { name: "MLFilterRender" },
            filters: [
              {
                data: {
                  type: "datetime",
                  op: "cn",
                  write: null,
                  min: null,
                  max: null,
                },
              },
            ],
          },
        ],

        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          props: {
            result: "data", // 配置响应结果列表字段
            total: "total", // 配置响应结果总页数字段
          },
          ajax: {
            query: ({ page, sorts, filters }) => {
              return new Promise((resolve) => {
                const firstSort = sorts[0];
                query({
                  filters: this.eipTableFilter(filters),
                  current: page.currentPage,
                  size: page.pageSize,
                  id: this.grid.extend.id,
                  sort: this.eipGridSort(sorts),
                }).then((result) => {
                  if (result.code == this.eipResultCode.success) {
                    resolve(result);
                  }
                  this.grid.loading = false;
                });
              });
            },
          },
        },
        data: [],
        extend: {
          id: null,
        },
      },
    };
  },
  components: { detail },
  created() {
    this.initTree();
  },
  mounted() {},
  methods: {
    /**
     * 用户详情
     */
    userBind(row) {
      let that = this;
      this.user.threeUserId = row.threeUserId;
      if (row.systemUserId) {
        that.$loading.show({ text: "解绑中..." });
        bindUserId({
          systemUserId: null,
          threeUserId: row.threeUserId,
        }).then((result) => {
          that.$loading.hide();
          that.$message.destroy();
          if (result.code === that.eipResultCode.success) {
            that.$message.success(result.msg);
            that.tableInit();
          } else {
            that.$message.error(result.msg);
          }
        });
      } else {
        this.user.visible = true;
      }
    },
    /**
     * 用户详情
     */
    userDetail(row) {
      this.detail.userId = row.systemUserId;
      this.detail.title = "用户详情-" + row.name;
      this.detail.visible = true;
    },
    /**
     * 选择
     */
    chosenUserOk(data) {
      let that = this;
      //弹出绑定用户
      that.$loading.show({ text: "绑定中..." });
      bindUserId({
        systemUserId: data[0].userId,
        threeUserId: this.user.threeUserId,
      }).then((result) => {
        that.$loading.hide();
        that.$message.destroy();
        if (result.code === that.eipResultCode.success) {
          that.$message.success(result.msg);
          that.tableInit();
        } else {
          that.$message.error(result.msg);
        }
      });
    },

    /**
     * 初始化数据
     */
    init() {
      this.tableInit();
      this.initTree();
    },
    /**
     * 树选中
     */
    select(electedKeys, e) {
      this.grid.extend.id = electedKeys[0];
      this.tableInit();
    },
    /**
     * 树图标
     */
    icon(props) {
      const { expanded } = props;
      if (props.children.length == 0) {
        return <a-icon type="file" />;
      }
      return <a-icon type={expanded ? "folder-open" : "folder"} />;
    },

    /**
     * 查询
     * @param {*} e
     */
    departmentSearch(e) {
      var that = this;
      this.department.data = this.$utils.clone(this.department.original, true);
      this.department.data = this.$utils.searchTree(
        this.department.data,
        (item) => {
          if (that.department.key) {
            var titlePinyin = pinyin.convert(item.title).toLowerCase();
            if (
              item.title
                .toLowerCase()
                .indexOf(that.department.key.toLowerCase()) > -1
            ) {
              return true;
            } else if (
              titlePinyin.indexOf(that.department.key.toLowerCase()) > -1
            ) {
              return true;
            } else {
              return false;
            }
          } else {
            return true;
          }
        },
        { children: "children" }
      );
    },
    /**
     *
     */
    initTree() {
      let that = this;
      that.department.spinning = true;
      tree().then((result) => {
        that.department.original = result.data;
        that.department.data = result.data;
        that.department.spinning = false;
      });
    },
    /**
     * 选择
     */
    chosenOrganizationTransfer() {
      let that = this;
      selectTableRow(
        that.$refs.xGrid,
        function (rows) {
          that.options.visible = true;
          that.options.userIds = rows.map((m) => m.userId).join(",");
        },
        that,
        false
      );
    },

    /**
     * 选择
     */
    chosenOrganizationOk(data) {
      let that = this;
      if (data.length != 0) {
        that.$loading.show({ text: "转移中" });
        transfer({
          userIds: this.options.userIds,
          organizationId: data.map((m) => m.key).join(","),
        })
          .then((result) => {
            that.$loading.hide();
            that.$message.destroy();
            if (result.code === that.eipResultCode.success) {
              that.$message.success(result.msg);
              that.tableInit();
            } else {
              that.$message.error(result.msg);
            }
          })
          .catch((err) => {
            that.$loading.hide();
            that.$message.destroy();
          });
      }
    },

    /**
     * 同步
     */
    asyncUser() {
      let that = this;
      that.$loading.show({ text: "获取中" });
      async()
        .then((result) => {
          that.$loading.hide();
          that.$message.destroy();
          if (result.code === that.eipResultCode.success) {
            that.$message.success(result.msg);
            that.tableInit();
          } else {
            that.$message.error(result.msg);
          }
        })
        .catch((err) => {
          that.$loading.hide();
          that.$message.destroy();
        });
    },

    /**
     * 同步
     */
    asyncUserToSystem() {
      let that = this;
      operationConfirm(
        "确定同步到系统用户,同步后人员关系发生变化",
        function () {
          that.$loading.show({ text: "同步中" });
          asyncToSystem().then((result) => {
            that.$loading.hide();
            that.$message.destroy();
            if (result.code === that.eipResultCode.success) {
              that.$message.success(result.msg);
              that.tableInit();
            } else {
              that.$message.error(result.msg);
            }
          });
        },
        that
      );
    },

    /**
     * 已导入用户数据,根据名称绑定企业微信用户
     */
    bindUser() {
      let that = this;
      operationConfirm(
        "确定根据名称绑定企业微信用户,请确保用户已在【系统用户】中进行导入",
        function () {
          that.$message.destroy();
          that.$loading.show({ text: "绑定中..." });
          bind().then((result) => {
            that.$loading.hide();
            that.$message.destroy();
            if (result.code === that.eipResultCode.success) {
              that.$message.success(result.msg);
              that.tableInit();
            } else {
              that.$message.error(result.msg);
            }
          });
        },
        that
      );
    },

    /**
     * 初始化流程按钮数据
     */
    tableInit() {
      this.$refs.xGrid.commitProxy("query");
    },

    //提示状态信息
    operateStatus(result) {
      if (result.code === this.eipResultCode.success) {
        this.tableInit();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.ant-tag {
  border-radius: 40px !important;
}

.img {
  width: 23px;
  height: 23px;
  border-radius: 50%;
}

/deep/ .run-list-user .ant-tag {
  cursor: pointer;
  padding: 0 7px 0 0 !important;
  border-radius: 50px !important;
}

/deep/ .run-list-user .ant-tag label {
  font-size: 12px;
  margin-left: 4px;
}
</style>
